/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.dubbo.common.extension;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.context.Lifecycle;
import org.apache.dubbo.common.extension.support.ActivateComparator;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;

import static java.util.Collections.sort;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX;

/**
 * {@link org.apache.dubbo.rpc.model.ApplicationModel}, {@code DubboBootstrap} and this class are
 * at present designed to be singleton or static (by itself totally static or uses some static fields).
 * So the instances returned from them are of process or classloader scope. If you want to support
 * multiple dubbo servers in a single process, you may need to refactor these three classes.
 * <p>
 * Load dubbo extensions
 * <ul>
 * <li>auto inject dependency extension </li>
 * <li>auto wrap extension in wrapper </li>
 * <li>default extension is an adaptive instance</li>
 * </ul>
 *
 * @see <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service%20Provider">Service Provider in Java 5</a>
 * @see org.apache.dubbo.common.extension.SPI
 * @see org.apache.dubbo.common.extension.Adaptive
 * @see org.apache.dubbo.common.extension.Activate
 */
public class ExtensionLoader<T> {

    private static final Logger logger = LoggerFactory.getLogger(ExtensionLoader.class);

    private static final String SERVICES_DIRECTORY = "META-INF/services/";

    private static final String DUBBO_DIRECTORY = "META-INF/dubbo/";

    private static final String DUBBO_INTERNAL_DIRECTORY = DUBBO_DIRECTORY + "internal/";

    private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*");

    private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<>(64);

    private static final ConcurrentMap<Class<?>, Object> EXTENSION_INSTANCES = new ConcurrentHashMap<>(64);

    private final Class<?> type;

    private final ExtensionFactory objectFactory;

    private final ConcurrentMap<Class<?>, String> cachedNames = new ConcurrentHashMap<>();

    private final Holder<Map<String, Class<?>>> cachedClasses = new Holder<>();

    private final Map<String, Object> cachedActivates = new ConcurrentHashMap<>();
    private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap<>();
    private final Holder<Object> cachedAdaptiveInstance = new Holder<>();
    private volatile Class<?> cachedAdaptiveClass = null;
    private String cachedDefaultName;
    private volatile Throwable createAdaptiveInstanceError;

    private Set<Class<?>> cachedWrapperClasses;

    private Map<String, IllegalStateException> exceptions = new ConcurrentHashMap<>();

    private static LoadingStrategy DUBBO_INTERNAL_STRATEGY = () -> DUBBO_INTERNAL_DIRECTORY;
    private static LoadingStrategy DUBBO_STRATEGY = () -> DUBBO_DIRECTORY;
    private static LoadingStrategy SERVICES_STRATEGY = () -> SERVICES_DIRECTORY;

    private static LoadingStrategy[] strategies = new LoadingStrategy[]{DUBBO_INTERNAL_STRATEGY, DUBBO_STRATEGY, SERVICES_STRATEGY};

    public static void setLoadingStrategies(LoadingStrategy... strategies) {
        ExtensionLoader.strategies = strategies;
    }

    private ExtensionLoader(Class<?> type) {
        this.type = type;
        /**
         * 这里是在创建ExtensionLoader的时候初始化的，ExtensionFactory有好几个实现类，这个也是从spi文件中读取的
         * 而getAdaptiveExtension()方法获取分为两步：
         * 1.如果ExtensionFactory的实现类中有加了@Adaptive注解的实现类，那么这个方法获取的就是加了注解的实现类；
         * 2.如果没有，就会去创建一个Adaptive的代理对象返回给objectFactory
         *
         * 其中有一个实现类是加了注解的AdaptiveExtensionFactory，
         * 所以这里getAdaptiveExtension()获取的就是AdaptiveExtensionFactory
         */
        objectFactory = (type == ExtensionFactory.class ? null :
                ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
    }

    private static <T> boolean withExtensionAnnotation(Class<T> type) {
        return type.isAnnotationPresent(SPI.class);
    }

    /**
     * 获取一个可扩展的加载器，就是SPI的加载器，这里是根据传过来的接口类型去获取的
     * 就是每一个接口都会单独创建一个ExtensionLoader可扩展的SPI加载器，比如说协议接口类Protocol这个接口
     * dubbo底层都是通过自身的spi机制获取对应的实现类，是根据Protocol这个接口类型获取的
     * dubbo的spi机制需要在配置文件中指定一个key，这个key可以是一个字符串，也可以是多个字符串，通过key来获取对应的实现类
     * 比如：
     * key1,key2=com.xxx.Impl,那么久可以通过key1或者key2获取到对应的接口实现类Impl，它的spi机制不同于jdk的spi机制
     * 如果说dubbo的spi配置文件中配置的实现类没有对应的key，那么这个实现类如果有一个构造方法是注入获取的key的话，那么
     * 就是dubbo的一种aop的实现，也就是Wrapper包装类
     *
     * @param type
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
        if (type == null) {
            throw new IllegalArgumentException("Extension type == null");
        }
        //SPI机制要求配置的都是接口类型才行
        if (!type.isInterface()) {
            throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
        }
//        并且这是个接口必须要加@SPI注解才行，否则都不能认为是dubbo中的spi机制所提供的接口
        if (!withExtensionAnnotation(type)) {
            throw new IllegalArgumentException("Extension type (" + type +
                    ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
        }

        /**
         * 先从缓存中获取数据，如果缓存中没有，表示第一次来根据接口获取接口对应的扩展类加载器，那么会创建这个这个扩展类加载器
         * 获取成功过后放入缓存中EXTENSION_LOADERS
         * EXTENSION_LOADERS:
         *   key:接口类型Class
         *   value:接口所对应的扩展类加载器ExtensionLoader
         */
        ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
        if (loader == null) {
            //创建一个新的扩展类加载器
            EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
            //放入缓存
            loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
        }
        return loader;
    }

    // For testing purposes only
    public static void resetExtensionLoader(Class type) {
        ExtensionLoader loader = EXTENSION_LOADERS.get(type);
        if (loader != null) {
            // Remove all instances associated with this loader as well
            Map<String, Class<?>> classes = loader.getExtensionClasses();
            for (Map.Entry<String, Class<?>> entry : classes.entrySet()) {
                EXTENSION_INSTANCES.remove(entry.getValue());
            }
            classes.clear();
            EXTENSION_LOADERS.remove(type);
        }
    }

    public static void destroyAll() {
        EXTENSION_INSTANCES.forEach((_type, instance) -> {
            if (instance instanceof Lifecycle) {
                Lifecycle lifecycle = (Lifecycle) instance;
                try {
                    lifecycle.destroy();
                } catch (Exception e) {
                    logger.error("Error destroying extension " + lifecycle, e);
                }
            }
        });
    }

    private static ClassLoader findClassLoader() {
        return ClassUtils.getClassLoader(ExtensionLoader.class);
    }

    public String getExtensionName(T extensionInstance) {
        return getExtensionName(extensionInstance.getClass());
    }

    public String getExtensionName(Class<?> extensionClass) {
        getExtensionClasses();// load class
        return cachedNames.get(extensionClass);
    }

    /**
     * This is equivalent to {@code getActivateExtension(url, key, null)}
     *
     * @param url url
     * @param key url parameter key which used to get extension point names
     * @return extension list which are activated.
     * @see #getActivateExtension(org.apache.dubbo.common.URL, String, String)
     */
    public List<T> getActivateExtension(URL url, String key) {
        return getActivateExtension(url, key, null);
    }

    /**
     * This is equivalent to {@code getActivateExtension(url, values, null)}
     *
     * @param url    url
     * @param values extension point names
     * @return extension list which are activated
     * @see #getActivateExtension(org.apache.dubbo.common.URL, String[], String)
     */
    public List<T> getActivateExtension(URL url, String[] values) {
        return getActivateExtension(url, values, null);
    }

    /**
     * This is equivalent to {@code getActivateExtension(url, url.getParameter(key).split(","), null)}
     *
     * @param url   url
     * @param key   url parameter key which used to get extension point names
     * @param group group
     * @return extension list which are activated.
     * @see #getActivateExtension(org.apache.dubbo.common.URL, String[], String)
     */
    public List<T> getActivateExtension(URL url, String key, String group) {
        String value = url.getParameter(key);
        return getActivateExtension(url, StringUtils.isEmpty(value) ? null : COMMA_SPLIT_PATTERN.split(value), group);
    }

    /**
     * Get activate extensions.
     *
     * @param url    url
     * @param values extension point names
     * @param group  group
     * @return extension list which are activated
     * @see org.apache.dubbo.common.extension.Activate
     */
    public List<T> getActivateExtension(URL url, String[] values, String group) {
        List<T> activateExtensions = new ArrayList<>();
        List<String> names = values == null ? new ArrayList<>(0) : Arrays.asList(values);
        if (!names.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) {
            getExtensionClasses();
            for (Map.Entry<String, Object> entry : cachedActivates.entrySet()) {
                String name = entry.getKey();
                Object activate = entry.getValue();

                String[] activateGroup, activateValue;

                if (activate instanceof Activate) {
                    activateGroup = ((Activate) activate).group();
                    activateValue = ((Activate) activate).value();
                } else if (activate instanceof com.alibaba.dubbo.common.extension.Activate) {
                    activateGroup = ((com.alibaba.dubbo.common.extension.Activate) activate).group();
                    activateValue = ((com.alibaba.dubbo.common.extension.Activate) activate).value();
                } else {
                    continue;
                }
                if (isMatchGroup(group, activateGroup)
                        && !names.contains(name)
                        && !names.contains(REMOVE_VALUE_PREFIX + name)
                        && isActive(activateValue, url)) {
                    activateExtensions.add(getExtension(name));
                }
            }
            activateExtensions.sort(ActivateComparator.COMPARATOR);
        }
        List<T> loadedExtensions = new ArrayList<>();
        for (int i = 0; i < names.size(); i++) {
            String name = names.get(i);
            if (!name.startsWith(REMOVE_VALUE_PREFIX)
                    && !names.contains(REMOVE_VALUE_PREFIX + name)) {
                if (DEFAULT_KEY.equals(name)) {
                    if (!loadedExtensions.isEmpty()) {
                        activateExtensions.addAll(0, loadedExtensions);
                        loadedExtensions.clear();
                    }
                } else {
                    loadedExtensions.add(getExtension(name));
                }
            }
        }
        if (!loadedExtensions.isEmpty()) {
            activateExtensions.addAll(loadedExtensions);
        }
        return activateExtensions;
    }

    private boolean isMatchGroup(String group, String[] groups) {
        if (StringUtils.isEmpty(group)) {
            return true;
        }
        if (groups != null && groups.length > 0) {
            for (String g : groups) {
                if (group.equals(g)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean isActive(String[] keys, URL url) {
        if (keys.length == 0) {
            return true;
        }
        for (String key : keys) {
            // @Active(value="key1:value1, key2:value2")
            String keyValue = null;
            if (key.contains(":")) {
                String[] arr = key.split(":");
                key = arr[0];
                keyValue = arr[1];
            }

            for (Map.Entry<String, String> entry : url.getParameters().entrySet()) {
                String k = entry.getKey();
                String v = entry.getValue();
                if ((k.equals(key) || k.endsWith("." + key))
                        && ((keyValue != null && keyValue.equals(v)) || (keyValue == null && ConfigUtils.isNotEmpty(v)))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Get extension's instance. Return <code>null</code> if extension is not found or is not initialized. Pls. note
     * that this method will not trigger extension load.
     * <p>
     * In order to trigger extension load, call {@link #getExtension(String)} instead.
     *
     * @see #getExtension(String)
     */
    @SuppressWarnings("unchecked")
    public T getLoadedExtension(String name) {
        if (StringUtils.isEmpty(name)) {
            throw new IllegalArgumentException("Extension name == null");
        }
        Holder<Object> holder = getOrCreateHolder(name);
        return (T) holder.get();
    }

    /**
     * 获取一个Holder对象，这个Holder包装了spi配置文件中key所对应的实现类对象
     * cachedInstances是一个map，里面存的就是key所对应的实现对象
     * @param name
     * @return
     */
    private Holder<Object> getOrCreateHolder(String name) {
        Holder<Object> holder = cachedInstances.get(name);
        if (holder == null) {
            cachedInstances.putIfAbsent(name, new Holder<>());
            holder = cachedInstances.get(name);
        }
        return holder;
    }

    /**
     * Return the list of extensions which are already loaded.
     * <p>
     * Usually {@link #getSupportedExtensions()} should be called in order to get all extensions.
     *
     * @see #getSupportedExtensions()
     */
    public Set<String> getLoadedExtensions() {
        return Collections.unmodifiableSet(new TreeSet<>(cachedInstances.keySet()));
    }

    public List<T> getLoadedExtensionInstances() {
        List<T> instances = new ArrayList<>();
        cachedInstances.values().forEach(holder -> instances.add((T) holder.get()));
        return instances;
    }

    public Object getLoadedAdaptiveExtensionInstances() {
        return cachedAdaptiveInstance.get();
    }

//    public T getPrioritizedExtensionInstance() {
//        Set<String> supported = getSupportedExtensions();
//
//        Set<T> instances = new HashSet<>();
//        Set<T> prioritized = new HashSet<>();
//        for (String s : supported) {
//
//        }
//
//    }

    /**
     * Find the extension with the given name. If the specified name is not found, then {@link IllegalStateException}
     * will be thrown.
     *
     * 根据spi中配置的名称获取所对应的实现类
     */

    @SuppressWarnings("unchecked")
    public T getExtension(String name) {
        if (StringUtils.isEmpty(name)) {
            throw new IllegalArgumentException("Extension name == null");
        }
        /**
         * 如果传入的名字为true，表示要获取一个默认的名字
         * 默认的名字是在@SPI（"")中配置的，如果配置了就有默认的名字，如果没有配置，那么是获取不到的
         * 反正就是如果传入的name为true，那么就需要在@SPI中配置名称，如果没有配置，就类似于传入了空字符串，在
         * getDefaultExtension会直接返回一个null
         */
        if ("true".equals(name)) {
            return getDefaultExtension();
        }
        final Holder<Object> holder = getOrCreateHolder(name);
        Object instance = holder.get();
        /**
         * 这里是来根据传入的名字获取一个名字所对应的实现类的对象，比如spi配置文件中配置的是
         * abc=com.xxx.Impl
         * 那么这里传入的是name=abc，最终得到的instance就是Impl的一个实例对象，实例对象是dubbo通过反射得到的一个对象
         *
         * 下面还有一个重要的概念就是并发里面的DCL，就是双重检查，当有多个线程进来的时候，关于DCL的就不说了，这里重要的是说一个
         * 设计思路，在DCL中需要加锁，但是下面的代码用了一个Holder来加锁，因为对于多个线程来说，只有获取同一个类型的对象时加锁才有意义
         * 否则你设计一个Object锁，那么这把锁就太粗了，因为不同的接口来获取对应是互不影响的，不应该拉入锁的控制，但是由于这里
         * 还没有创建对象，所以null是不能作为锁的，所以dubbo的设计者将这里的instance对象作为一个属性包装到Hodler里面，那么这里Hodler
         * 肯定是不为空的，只是刚开始其中的属性value是空的，但是不影响，所以这里的锁粒度就变细了，这样的并发空控制才是性能上的最优选择
         */
        if (instance == null) {
            synchronized (holder) {
                instance = holder.get();
                if (instance == null) {
                    //创建一个key所对应的实例对象
                    instance = createExtension(name);
                    holder.set(instance);
                }
            }
        }
        return (T) instance;
    }

    /**
     * Get the extension by specified name if found, or {@link #getDefaultExtension() returns the default one}
     *
     * @param name the name of extension
     * @return non-null
     */
    public T getOrDefaultExtension(String name) {
        return containsExtension(name) ? getExtension(name) : getDefaultExtension();
    }

    /**
     * Return default extension, return <code>null</code> if it's not configured.
     * 根据传入的name=true去获取@SPI中配置的一个默认的name，然后在回调getExtension
     * 获取扩展实现类对象
     */
    public T getDefaultExtension() {
        getExtensionClasses();
        if (StringUtils.isBlank(cachedDefaultName) || "true".equals(cachedDefaultName)) {
            return null;
        }
        return getExtension(cachedDefaultName);
    }

    public boolean hasExtension(String name) {
        if (StringUtils.isEmpty(name)) {
            throw new IllegalArgumentException("Extension name == null");
        }
        Class<?> c = this.getExtensionClass(name);
        return c != null;
    }

    public Set<String> getSupportedExtensions() {
        Map<String, Class<?>> clazzes = getExtensionClasses();
        return Collections.unmodifiableSet(new TreeSet<>(clazzes.keySet()));
    }

    public Set<T> getSupportedExtensionInstances() {
        List<T> instances = new LinkedList<>();
        Set<String> supportedExtensions = getSupportedExtensions();
        if (CollectionUtils.isNotEmpty(supportedExtensions)) {
            for (String name : supportedExtensions) {
                instances.add(getExtension(name));
            }
        }
        // sort the Prioritized instances
        sort(instances, Prioritized.COMPARATOR);
        return new LinkedHashSet<>(instances);
    }

    /**
     * Return default extension name, return <code>null</code> if not configured.
     */
    public String getDefaultExtensionName() {
        getExtensionClasses();
        return cachedDefaultName;
    }

    /**
     * Register new extension via API
     *
     * @param name  extension name
     * @param clazz extension class
     * @throws IllegalStateException when extension with the same name has already been registered.
     */
    public void addExtension(String name, Class<?> clazz) {
        getExtensionClasses(); // load classes

        if (!type.isAssignableFrom(clazz)) {
            throw new IllegalStateException("Input type " +
                    clazz + " doesn't implement the Extension " + type);
        }
        if (clazz.isInterface()) {
            throw new IllegalStateException("Input type " +
                    clazz + " can't be interface!");
        }

        if (!clazz.isAnnotationPresent(Adaptive.class)) {
            if (StringUtils.isBlank(name)) {
                throw new IllegalStateException("Extension name is blank (Extension " + type + ")!");
            }
            if (cachedClasses.get().containsKey(name)) {
                throw new IllegalStateException("Extension name " +
                        name + " already exists (Extension " + type + ")!");
            }

            cachedNames.put(clazz, name);
            cachedClasses.get().put(name, clazz);
        } else {
            if (cachedAdaptiveClass != null) {
                throw new IllegalStateException("Adaptive Extension already exists (Extension " + type + ")!");
            }

            cachedAdaptiveClass = clazz;
        }
    }

    /**
     * Replace the existing extension via API
     *
     * @param name  extension name
     * @param clazz extension class
     * @throws IllegalStateException when extension to be placed doesn't exist
     * @deprecated not recommended any longer, and use only when test
     */
    @Deprecated
    public void replaceExtension(String name, Class<?> clazz) {
        getExtensionClasses(); // load classes

        if (!type.isAssignableFrom(clazz)) {
            throw new IllegalStateException("Input type " +
                    clazz + " doesn't implement Extension " + type);
        }
        if (clazz.isInterface()) {
            throw new IllegalStateException("Input type " +
                    clazz + " can't be interface!");
        }

        if (!clazz.isAnnotationPresent(Adaptive.class)) {
            if (StringUtils.isBlank(name)) {
                throw new IllegalStateException("Extension name is blank (Extension " + type + ")!");
            }
            if (!cachedClasses.get().containsKey(name)) {
                throw new IllegalStateException("Extension name " +
                        name + " doesn't exist (Extension " + type + ")!");
            }

            cachedNames.put(clazz, name);
            cachedClasses.get().put(name, clazz);
            cachedInstances.remove(name);
        } else {
            if (cachedAdaptiveClass == null) {
                throw new IllegalStateException("Adaptive Extension doesn't exist (Extension " + type + ")!");
            }

            cachedAdaptiveClass = clazz;
            cachedAdaptiveInstance.set(null);
        }
    }

    /**
     * 这里就是去获取一个@Adaptive的实现类对象或者创建一个Adaptive代理对象
     * @return
     */
    @SuppressWarnings("unchecked")
    public T getAdaptiveExtension() {
        Object instance = cachedAdaptiveInstance.get();
        if (instance == null) {
            if (createAdaptiveInstanceError != null) {
                throw new IllegalStateException("Failed to create adaptive instance: " +
                        createAdaptiveInstanceError.toString(),
                        createAdaptiveInstanceError);
            }

            //DCL控制
            synchronized (cachedAdaptiveInstance) {
                instance = cachedAdaptiveInstance.get();
                if (instance == null) {
                    try {
                        //创建或者获取一个对象
                        instance = createAdaptiveExtension();
                        cachedAdaptiveInstance.set(instance);
                    } catch (Throwable t) {
                        createAdaptiveInstanceError = t;
                        throw new IllegalStateException("Failed to create adaptive instance: " + t.toString(), t);
                    }
                }
            }
        }

        return (T) instance;
    }

    private IllegalStateException findException(String name) {
        for (Map.Entry<String, IllegalStateException> entry : exceptions.entrySet()) {
            if (entry.getKey().toLowerCase().contains(name.toLowerCase())) {
                return entry.getValue();
            }
        }
        StringBuilder buf = new StringBuilder("No such extension " + type.getName() + " by name " + name);


        int i = 1;
        for (Map.Entry<String, IllegalStateException> entry : exceptions.entrySet()) {
            if (i == 1) {
                buf.append(", possible causes: ");
            }

            buf.append("\r\n(");
            buf.append(i++);
            buf.append(") ");
            buf.append(entry.getKey());
            buf.append(":\r\n");
            buf.append(StringUtils.toString(entry.getValue()));
        }
        return new IllegalStateException(buf.toString());
    }

    /**
     * 创建一个name所对应的实例对象
     *
     * @param name
     * @return
     */


    @SuppressWarnings("unchecked")
    private T createExtension(String name) {
         //读取spi配置文件将配置文件中配置的扩展类，包括@Adaptive,aop包装类都读取放入到缓存中
        Class<?> clazz = getExtensionClasses().get(name);
        //如果从读取的缓存数据中没有获取到name对应的扩展类，就直接报错
        if (clazz == null) {
            throw findException(name);
        }
        try {
            /**
             * 根据name获取的扩展类对象在第一次过后是会放入缓存的，如果缓存中没有获取到
             * 就会去创建，创建好了就放入缓存
             * 这里可以理解为spring中的IOC功能
             */
            T instance = (T) EXTENSION_INSTANCES.get(clazz);
            if (instance == null) {
                EXTENSION_INSTANCES.putIfAbsent(clazz, clazz.newInstance());
                instance = (T) EXTENSION_INSTANCES.get(clazz);
            }
            //依赖注入DI，比较复杂一点，但是比spring要好一点，没有spring的复杂
            injectExtension(instance);
            //cachedWrapperClasses是在读取spi配置文件的时候将所有的包装类（AOP）都缓存到了
            //cachedWrapperClasses,这里就是来创建aop的代理对象，类似于
            /**
             * black=org.apache.dubbo.BlackCar
             * org.apache.dubbo.CarWrapper
             * 通过black获取到的不是BlackCar，而是CarWrapper，是对BlackCar的一个代理
             */
            Set<Class<?>> wrapperClasses = cachedWrapperClasses;
            if (CollectionUtils.isNotEmpty(wrapperClasses)) {
                for (Class<?> wrapperClass : wrapperClasses) {
                    /**
                     * 所以在dubbo的aop中，比如CarWrapper是需要提供一个只有一个参数的构造，而且这个参数还必须是type类型
                     * 这里也就是Car接口类型，而BlackCar也是Car接口类型，否则要报错
                     * 执行了wrapperClass.getConstructor(type).newInstance(instance)过后得到的是CarWrapper，dubbo和spring一样
                     * 需要对其进行DI，就是属性注入，dubbo中这个版本的属性注入只能通过set方法，也就是injectExtension方法
                     */
                    instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
                }
            }
            //最后一步初始化生命周期方法
            initExtension(instance);
            return instance;
        } catch (Throwable t) {
            throw new IllegalStateException("Extension instance (name: " + name + ", class: " +
                    type + ") couldn't be instantiated: " + t.getMessage(), t);
        }
    }

    private boolean containsExtension(String name) {
        return getExtensionClasses().containsKey(name);
    }

    /**
     * 这是dubbo中的DI，就是在得到一个扩展类的时候，如果扩展类中有需要注入的属性，
     * 那么dubbo都会为其注入的，dubbo注入的模式在这个版本会从spring容器中去获取bean
     * 如果获取到了就会注入，在spring容器中获取是通过byname再bytype
     * 如果spring容器中没有获取到，就会使用dubbo本身提供的一些机制去注入
     * 但是是否有顺序，这个好像是没有顺序的
     * @param instance
     * @return
     */
    private T injectExtension(T instance) {

        //objectFactory是在创建扩展类加载器的时候初始化的
        if (objectFactory == null) {
            return instance;
        }

        try {
            //这里就是获取BlackPerson（比如示例的类）中的所有的方法，进行循环判断
            for (Method method : instance.getClass().getMethods()) {
                //首先判断是否是一个set方法，dubbo的DI只支持set方法注入
                if (!isSetter(method)) {
                    continue;
                }
                /**
                 * Check {@link DisableInject} to see if we need auto injection for this property
                 * 判断这个set方法是否不需要注入，如果加入了@DisableInject注解，表示不需要dubbo帮你注入
                 */
                if (method.getAnnotation(DisableInject.class) != null) {
                    continue;
                }
                //获取set方法的第一个参数，比如setCar(Car car),这个获取的就是Car这个类型
                Class<?> pt = method.getParameterTypes()[0];
                //过滤掉set参数中一些私有的类和比如Date String 等等这些，这些不需要进行注入
                if (ReflectUtils.isPrimitives(pt)) {
                    continue;
                }

                try {
                    //根据set方法名称获取注入的属性，比如setCar，那么property获取的就是car这个名字
                    String property = getSetterProperty(method);
                    //pt=参数的类型（com.xxx.Car)，property就是注入的参数的名字(car)
                    //这个的objectFactory类型是AdaptiveExtensionFactory
                    Object object = objectFactory.getExtension(pt, property);
                    if (object != null) {
                        //创建出Car这个对象过后，调用set方法进行注入赋值
                        method.invoke(instance, object);
                    }
                } catch (Exception e) {
                    logger.error("Failed to inject via method " + method.getName()
                            + " of interface " + type.getName() + ": " + e.getMessage(), e);
                }

            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return instance;
    }

    private void initExtension(T instance) {
        if (instance instanceof Lifecycle) {
            Lifecycle lifecycle = (Lifecycle) instance;
            lifecycle.initialize();
        }
    }

    /**
     * get properties name for setter, for instance: setVersion, return "version"
     * <p>
     * return "", if setter name with length less than 3
     */
    private String getSetterProperty(Method method) {
        return method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
    }

    /**
     * return true if and only if:
     * <p>
     * 1, public
     * <p>
     * 2, name starts with "set"
     * <p>
     * 3, only has one parameter
     */
    private boolean isSetter(Method method) {
        return method.getName().startsWith("set")
                && method.getParameterTypes().length == 1
                && Modifier.isPublic(method.getModifiers());
    }

    private Class<?> getExtensionClass(String name) {
        if (type == null) {
            throw new IllegalArgumentException("Extension type == null");
        }
        if (name == null) {
            throw new IllegalArgumentException("Extension name == null");
        }
        return getExtensionClasses().get(name);
    }

    /**
     * 加载spi配置文件，将所有的spi配置文件进行加载，如果第一次加载的话就进行读取
     * 第一次加载完成过后放入缓存，后面的过来加载就直接从缓存获取加载spi配置
     * @return
     */
    private Map<String, Class<?>> getExtensionClasses() {
        Map<String, Class<?>> classes = cachedClasses.get();
        //相同的DCL（Double Check Lock）控制
        if (classes == null) {
            synchronized (cachedClasses) {
                classes = cachedClasses.get();
                if (classes == null) {
                    //第一次加载，读取spi配置文件加载，返回一个map放入缓存
                    classes = loadExtensionClasses();
                    //放入缓存cachedClasses中
                    cachedClasses.set(classes);
                }
            }
        }
        return classes;
    }

    /**
     * synchronized in getExtensionClasses
     * 加载spi配置文件
     */
    private Map<String, Class<?>> loadExtensionClasses() {
        cacheDefaultExtensionName();

        //加载的所有的spi配置信息都放入到extensionClasses中
        Map<String, Class<?>> extensionClasses = new HashMap<>();

        /**
         * strategies:
         *   META-INF/dubbo/internal
         *   META-INF/dubbo
         *   META-INF/services
         * dubbo从这三个目录中加载spi文件，所以文件放在这三个目录都是可以的，优先级如上
         */
        for (LoadingStrategy strategy : strategies) {
            /**
             * 下面两个方法都是一样的，都是加载spi配置文件，目录都是一样的，
             * 但是第二个方法是为了兼容之前的包命名规则
             */
            loadDirectory(extensionClasses, strategy.directory(), type.getName(), strategy.preferExtensionClassLoader(), strategy.excludedPackages());
            loadDirectory(extensionClasses, strategy.directory(), type.getName().replace("org.apache", "com.alibaba"), strategy.preferExtensionClassLoader(), strategy.excludedPackages());
        }

        return extensionClasses;
    }

    /**
     * extract and cache default extension name if exists
     */
    private void cacheDefaultExtensionName() {
        /**
         * 这里是去获取默认的SPI名字的，在接口上配置了@SPI("NAME")那么这个NAME就是一个默认的名字，会放入到
         * cachedDefaultName中，并且是只有一个的，不能多个
         */
        final SPI defaultAnnotation = type.getAnnotation(SPI.class);
        if (defaultAnnotation == null) {
            return;
        }

        String value = defaultAnnotation.value();
        if ((value = value.trim()).length() > 0) {
            String[] names = NAME_SEPARATOR.split(value);
            if (names.length > 1) {
                throw new IllegalStateException("More than 1 default extension name on extension " + type.getName()
                        + ": " + Arrays.toString(names));
            }
            if (names.length == 1) {
                cachedDefaultName = names[0];
            }
        }
    }

    private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type) {
        loadDirectory(extensionClasses, dir, type, false);
    }

    private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type,
                               boolean extensionLoaderClassLoaderFirst, String... excludedPackages) {
        //type就是一个接口的全限定名,dir就是目录，所以fileName=META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol
        String fileName = dir + type;
        try {
            /**
             * 1.找到ExtensionLoader所在的类加载器；
             * 2.通过类加载器去读取 fileName
             *
             */
            Enumeration<java.net.URL> urls = null;
            ClassLoader classLoader = findClassLoader();

            // try to load from ExtensionLoader's ClassLoader first
            if (extensionLoaderClassLoaderFirst) {
                ClassLoader extensionLoaderClassLoader = ExtensionLoader.class.getClassLoader();
                if (ClassLoader.getSystemClassLoader() != extensionLoaderClassLoader) {
                    urls = extensionLoaderClassLoader.getResources(fileName);
                }
            }

            if (urls == null || !urls.hasMoreElements()) {
                if (classLoader != null) {
                    urls = classLoader.getResources(fileName);
                } else {
                    urls = ClassLoader.getSystemResources(fileName);
                }
            }

            if (urls != null) {
                while (urls.hasMoreElements()) {
                    java.net.URL resourceURL = urls.nextElement();
                    //读取每一个文件，比如org.apache.dubbo.rpc.Protocol这个spi的配置文件，然后加载读取
                    loadResource(extensionClasses, classLoader, resourceURL, excludedPackages);
                }
            }
        } catch (Throwable t) {
            logger.error("Exception occurred when loading extension class (interface: " +
                    type + ", description file: " + fileName + ").", t);
        }
    }

    private void loadResource(Map<String, Class<?>> extensionClasses, ClassLoader classLoader,
                              java.net.URL resourceURL, String... excludedPackages) {
        try {
            //逐行读取，每一行的配置是key=实现类或者只有实现类或者只有注释或者是在key=实现类后的注释，内容如下：
            /**
             * #协议的配置
             * protocol=or.apache.xxx.HttpProtocol
             * key=com.xxx.Impl #测试的SPI
             */
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    //这里要过滤掉注释的，就上面所写的格式，如果遇到#的，那么截取#号前面的字符串，如果截取到#前的字符长度大于0表示是”key=com.xxx.Impl #测试的SPI“这种类型
                    //否则就是整行都是注释
                    final int ci = line.indexOf('#');
                    if (ci >= 0) {
                        //如果#大于0，那么看下#号前面是否有字符
                        line = line.substring(0, ci);
                    }
                    line = line.trim();
                    //line的长度大于0，表示有需要处理的行
                    if (line.length() > 0) {
                        try {
                            String name = null;
                            //读取格式key=value的格式，如果没有key，那么line=value
                            int i = line.indexOf('=');
                            if (i > 0) {
                                name = line.substring(0, i).trim();
                                line = line.substring(i + 1).trim();
                            }
                            //如果line大于0，那么如果line是不在排除之外的包下就进入加载的方法loadClass
                            if (line.length() > 0 && !isExcluded(line, excludedPackages)) {
                                loadClass(extensionClasses, resourceURL, Class.forName(line, true, classLoader), name);
                            }
                        } catch (Throwable t) {
                            IllegalStateException e = new IllegalStateException("Failed to load extension class (interface: " + type + ", class line: " + line + ") in " + resourceURL + ", cause: " + t.getMessage(), t);
                            exceptions.put(line, e);
                        }
                    }
                }
            }
        } catch (Throwable t) {
            logger.error("Exception occurred when loading extension class (interface: " +
                    type + ", class file: " + resourceURL + ") in " + resourceURL, t);
        }
    }

    private boolean isExcluded(String className, String... excludedPackages) {
        if (excludedPackages != null) {
            for (String excludePackage : excludedPackages) {
                if (className.startsWith(excludePackage + ".")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 读取spi配置文件中的实现类，也就是扩展类，接口对应的扩展类，加载到map中
     * 得到扩展类的全限定名，然后通过反射得到实例放入map
     * @param extensionClasses
     * @param resourceURL
     * @param clazz
     * @param name
     * @throws NoSuchMethodException
     */
    private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name) throws NoSuchMethodException {
        /**
         * type是接口，也就是接口的class类型，而clazz是在spi配置文件中配置的类全限定名得到的class
         * 所有必须是type的实现类，否则就要报错
         */
        if (!type.isAssignableFrom(clazz)) {
            throw new IllegalStateException("Error occurred when loading extension class (interface: " +
                    type + ", class line: " + clazz.getName() + "), class "
                    + clazz.getName() + " is not subtype of interface.");
        }
        /**
         * 判断扩展实现类是否是Adaptive类，在dubbo的依赖注入，也就是属性注入的时候，如果
         * 你指定了一个注入属性的实现类加了@Adaptive注解的话，那么就不用传入Url对象进行参数传递，换句话说就是
         * 比如通过spi获取到BlackPerson中有一个属性Car car，而这个car的有一个实现类中有一个加了
         * @Adaptive注解，那么dubbo就不用给你生成car的这个代理对象进行赋值了，依赖注入会直接将这个
         * 加了@Adaptive注解的实现类直接注入到car这个属性里面去，还有一个限制就是如果car的实现类中如果超过1个
         * 都加了@Adaptive注解，那么也是不生效的，所以car的实现类中只能加一个@Adaptive注解，表示属性的注入都
         * 使用这个作为注入的实现类，否则就只能通过URL对象进行参数传递
         */
        if (clazz.isAnnotationPresent(Adaptive.class)) {
             //将加了@Adaptive注解的实现类的class类型缓存到一个对象cachedAdaptiveClass中，后面如果
            //有那个类中使用了clazz作为属性的时候可以直接注入
            cacheAdaptiveClass(clazz);
        } else if (isWrapperClass(clazz)) {
            //如果是包装类，也就是dubbo这里提供的aop机制，那么
            /**
             * 比如说spi配置是这样的
             * black=org.apache.dubbo.BlackCar
             * org.apache.dubbo.CarWrapper
             * 而CarWrapper中有一个构造方法，参数类型是Car，而CarWrapper也是实现了Car，BlackCar也是
             * 实现了Car，那么通过black获取到的对象其实就是CarWrapper，CarWrapper中实现了Car的接口方法
             * 所以在嗲用BlackCar的接口方法时，会先调用CarWrapper中的接口方法，再会去调用BlackCar的接口
             * 方法，这就是简单的aop机制，dubbo通过包装类来实现的，如果一个类具有包装类（aop），那么它是不
             * 需要配置key的，在spi中直接配置一个实现类的全限定名就可以了
             */
            //将这个包装类aop添加到缓存中
            cacheWrapperClass(clazz);
        } else {
            /**
             * 如果不是上面的两种类型，那么要获取这个实现类的一个默认的空构造方法，也就是说Car的实现类
             * 中必须要有一个空的构造方法
             */
            clazz.getConstructor();
            if (StringUtils.isEmpty(name)) {
                //如果说在spi的配置文件中没有配置key，但是又不是适配器类，也不是包装类，那么就需要配置
                //你的这个实现类是否配置了@Extension，如果配置了就获取Extension中的配置名称，如果
                //还是没有就报错,但是这个@Extension已经不推荐使用了，所以在配置文件中配置key才是
                //最好的做法
                name = findAnnotationName(clazz);
                if (name.length() == 0) {
                    throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + resourceURL);
                }
            }

            /**
             * 程序执行到这里的时候，必要要满足的条件是需要有一个name，和name对应的class
             * 名字可以有多个，比如key1,key2,key3=com.xx.Impl
             */

            String[] names = NAME_SEPARATOR.split(name);
            if (ArrayUtils.isNotEmpty(names)) {
                //Activate的处理
                cacheActivateClass(clazz, names[0]);

                for (String n : names) {
                    //将class对应的名字添加到map cachedNames中缓存起来
                    cacheName(clazz, n);
                    //将名字为n的clazz添加到map extensionClasses中缓存起来
                    saveInExtensionClass(extensionClasses, clazz, n);
                }
            }
        }
    }

    /**
     * cache name
     */
    private void cacheName(Class<?> clazz, String name) {
        if (!cachedNames.containsKey(clazz)) {
            cachedNames.put(clazz, name);
        }
    }

    /**
     * put clazz in extensionClasses
     */
    private void saveInExtensionClass(Map<String, Class<?>> extensionClasses, Class<?> clazz, String name) {
        Class<?> c = extensionClasses.get(name);
        if (c == null) {
            extensionClasses.put(name, clazz);
        } else if (c != clazz) {
            String duplicateMsg = "Duplicate extension " + type.getName() + " name " + name + " on " + c.getName() + " and " + clazz.getName();
            logger.error(duplicateMsg);
            throw new IllegalStateException(duplicateMsg);
        }
    }

    /**
     * cache Activate class which is annotated with <code>Activate</code>
     * <p>
     * for compatibility, also cache class with old alibaba Activate annotation
     */
    private void cacheActivateClass(Class<?> clazz, String name) {
        Activate activate = clazz.getAnnotation(Activate.class);
        if (activate != null) {
            cachedActivates.put(name, activate);
        } else {
            // support com.alibaba.dubbo.common.extension.Activate
            com.alibaba.dubbo.common.extension.Activate oldActivate = clazz.getAnnotation(com.alibaba.dubbo.common.extension.Activate.class);
            if (oldActivate != null) {
                cachedActivates.put(name, oldActivate);
            }
        }
    }

    /**
     * cache Adaptive class which is annotated with <code>Adaptive</code>
     */
    private void cacheAdaptiveClass(Class<?> clazz) {
        if (cachedAdaptiveClass == null) {
            cachedAdaptiveClass = clazz;
        } else if (!cachedAdaptiveClass.equals(clazz)) {
            throw new IllegalStateException("More than 1 adaptive class found: "
                    + cachedAdaptiveClass.getName()
                    + ", " + clazz.getName());
        }
    }

    /**
     * cache wrapper class
     * <p>
     * like: ProtocolFilterWrapper, ProtocolListenerWrapper
     */
    private void cacheWrapperClass(Class<?> clazz) {
        if (cachedWrapperClasses == null) {
            cachedWrapperClasses = new ConcurrentHashSet<>();
        }
        cachedWrapperClasses.add(clazz);
    }

    /**
     * test if clazz is a wrapper class
     * <p>
     * which has Constructor with given class type as its only argument
     */
    private boolean isWrapperClass(Class<?> clazz) {
        try {
            //判断是否是type，比如Car的包装类（aop类），简单粗暴的判断，直接
            //获取包装类的构造方法，这个构造方法需要的参数类型就是Car，否则直接到异常，返回fasle，就不是一个aop
            clazz.getConstructor(type);
            return true;
        } catch (NoSuchMethodException e) {
            return false;
        }
    }

    @SuppressWarnings("deprecation")
    private String findAnnotationName(Class<?> clazz) {
        org.apache.dubbo.common.Extension extension = clazz.getAnnotation(org.apache.dubbo.common.Extension.class);
        if (extension != null) {
            return extension.value();
        }

        String name = clazz.getSimpleName();
        if (name.endsWith(type.getSimpleName())) {
            name = name.substring(0, name.length() - type.getSimpleName().length());
        }
        return name.toLowerCase();
    }

    @SuppressWarnings("unchecked")
    private T createAdaptiveExtension() {
        try {
            //创建出的这个对象如果还有属性要注入，也一样的调用DI；生成了代理类获取或者Adaptive实现类过后直接反射创建一个对象
            return injectExtension((T) getAdaptiveExtensionClass().newInstance());
        } catch (Exception e) {
            throw new IllegalStateException("Can't create adaptive extension " + type + ", cause: " + e.getMessage(), e);
        }
    }

    private Class<?> getAdaptiveExtensionClass() {
        //加载读取spi，如果已经加载了的话是不用加载的，这里是一个双重保险的效果
        getExtensionClasses();
        //cachedAdaptiveClass这个对象就是在读取spi文件时，如果这个发现了扩展类（实现类）中是一个加了@Adaptive注解的实现类，
        // 那么会赋值给cachedAdaptiveClass，需要注意的是一种类型的，比如Car这个接口类型，只能有一个@Adaptive注解的实现类
        if (cachedAdaptiveClass != null) {
            return cachedAdaptiveClass;
        }
        //如果没有加这个注解，下面就创建一个代理对象Adaptive$Car
        return cachedAdaptiveClass = createAdaptiveExtensionClass();
    }

    private Class<?> createAdaptiveExtensionClass() {
        //通过JDK的字节码生成去创建一个代码文件
        /**
         * 这里需要注意的是生成代理类的代码文件中要满足的条件的是要代理的对象比如Car，那么生成的代理对象是
         * public class Adaptive$Car implements Car
         * 所以这个代理类也是要实现了接口Car中的所有方法，而这些方法都必须要满足的两个条件：
         * 1.方法上面必须加@Adaptive注解；
         * 2.方法的参数中必须要有URL参数；
         * 如果没有加@Adaptive，那么这个方法也会生成，但是调用的时候会直接跑不支持之类的一些异常；
         * 如果方法中没有加URL参数，那么启动就直接报错，必须要有Url，因为你想，生成的代理类，当代理类真正调用Car的实现类的时候总要知道
         * 调用Car的那个实现类，所以就必须使用URL的addParameter来添加参数，然后传入到代理中
         */
        String code = new AdaptiveClassCodeGenerator(type, cachedDefaultName).generate();
        ClassLoader classLoader = findClassLoader();
        /**
         * 编码创建的代码文件，将其编译成一个java类对象，下面的第一行代码需要注意的是
         * 也是通过spi的机制去加载的，而且最后也通过getAdaptiveExtension()去获取了一个spi中的扩展类，这个扩展类
         * 也是默认获取的加了@Adaptive的，和之前的对象工厂objectFactory的处理方式一致，所以要找的spi文件就是：
         * org.apache.dubbo.common.compiler.Compiler这个文件，这个文件的内容如下：
         *    adaptive=org.apache.dubbo.common.compiler.support.AdaptiveCompiler
         *    jdk=org.apache.dubbo.common.compiler.support.JdkCompiler
         *    javassist=org.apache.dubbo.common.compiler.support.JavassistCompiler
         *    只有AdaptiveCompiler是加了@Adaptive注解的，所以这里的compile编译就是调用的AdaptiveCompiler中的compile方法进行编译的
         *    编译成功生成一个class，这个class就是Adaptive$Car（比如我的接口是Car）,就是创建了一个代理对象的class
         *    或者说你传入的对象不一定是URL这个对象，但是参数必须传入，而传入的参数中必须能够有方法getUrl这个方法才行
         */
        org.apache.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(org.apache.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();
        return compiler.compile(code, classLoader);
    }

    @Override
    public String toString() {
        return this.getClass().getName() + "[" + type.getName() + "]";
    }

}
